<?php


namespace app\api\controller;

use app\common\constant\TemplateConstant;
use app\common\controller\Alisms;
use think\Db;
use think\Exception;
use app\common\model\ViperUser;
use app\common\service\CommonService;
use app\common\service\FeiEPrintService;
use app\common\service\TicketService;
use app\common\model\ViperCardRechargeLog;
use app\api\validate\ViperCard as ViperCardValidate;
use app\common\model\ViperCard as ViperCardModel;
use think\Validate;

/**
 * 会员卡首页控制器
 * @package app\index\controller
 */
class ViperCard extends Auth
{

    public $noNeedLogin = '';

    /**
     * 会员卡开卡
     */
    public function add()
    {
        $data = $this->request->post();
        $validate = new ViperCardValidate();
        if (!$validate->check($data)) {
            $this->result($validate->getError(), '', 204);
        }

        $amount = 0;
        $give_amount = 0;
        switch ($data['template_type']) {
            case TemplateConstant::TEMPLATE_TYPE_DEFAULT ://会员卡
                $data['recharge_template_id'] = $data['template_id'];
                break;
            case TemplateConstant::TEMPLATE_TYPE_NUMBER ://次卡
                $data['number_template_id'] = $data['template_id'];
                break;
            case TemplateConstant::TEMPLATE_TYPE_MONTH ://月卡
                $data['month_template_id'] = $data['template_id'];
                break;
            case TemplateConstant::TEMPLATE_TYPE_AMOUNT ://实际金额充值
                $amount = $data['amount'];
                $give_amount = $data['give_amount'];
                break;
        }

        $user = ViperUser::where(['phone' => $data['mobile']])->find();
        $temp_arr = [
            'mobile' => $data['mobile'],
            //'card_no' => $data['card_no'],
            'viper_user_id' => !empty($user['id']) ? $user['id'] : 0,
            'user_id' => $this->userInfo['id'],
            'is_receiver_message' => $data['is_receiver_message'],
            'name' => $data['name'],
            'gender' => $data['gender'],
            'sale_id' => $data['sale_id'],
            'type' => $data['type'],
            'viper_type_id' => $data['viper_type_id'],
            'birthday' => strtotime($data['birthday']),
            'pay_content' => $data['pay_content'],
            'neima' => $data['neima'],
            'store_id' => $this->userInfo['store_id'],
            'amount' => $amount,
            'total_amount' => $amount,
            'give_amount' => $give_amount,
            'give_total_amount' => $give_amount,
            'open_content' => $data['open_content'],
            'template_id' => $data['template_id'],
            'template_type' => $data['template_type'],
        ];

        //开卡
        ViperCardModel::openCard($temp_arr, $this->userInfo);

        $this->result('操作成功', '', 200);
    }


    /**
     * 会员管理---会员卡列表
     * mobile  card_no
     */
    public function lists()
    {
        $data = $this->request->post();
        if (!isset($data['limit']) || empty($data['limit'])) {
            $data['limit'] = '10';
        }
        $sql = ViperCardModel::alias('v')
            ->field('v.id,v.name as user_name,v.mobile,v.card_no,v.amount,t.name,uv.avatar,v.birthday,v.gender,v.is_receiver_message,v.amount,v.total_amount,v.give_total_amount,v.amount,v.give_amount,v.score,v.status')
            ->leftJoin('dp_qt_viper_type t', 't.id=v.viper_type_id')
            ->leftJoin('dp_qt_user_viper uv', 'uv.id=v.user_id')
            ->where(['v.store_id' => $this->userInfo['store_id']]);
        //手机号搜索
        if (isset($data['mobile']) && !empty($data['mobile'])) {
            $sql = $sql->where(['v.mobile' => $data['mobile']]);
        }
        //卡号搜索
        if (isset($data['card_no']) && !empty($data['card_no'])) {
            $sql = $sql->where(['v.card_no' => $data['card_no']]);
        }
        //卡类型
        if (isset($data['viper_type_id']) && !empty($data['viper_type_id'])) {
            $sql = $sql->where(['v.viper_type_id' => $data['viper_type_id']]);
        }
        //姓名搜索
        if (isset($data['name']) && !empty($data['name'])) {
            $sql = $sql->where(['v.name' => $data['name']]);
        }
        //状态搜索
        if (isset($data['status']) && !empty($data['status'])) {
            $sql = $sql->where(['v.status' => $data['status']]);
        }
        //绑定状态搜索
        if (isset($data['bind_status']) && !empty($data['bind_status'])) {
            $sql = $sql->where(['v.bind_status' => $data['bind_status']]);
        }
        //开卡时间
        if (isset($getData['start_create_time']) && !empty($getData['start_create_time']) && isset($getData['end_create_time']) && !empty($getData['end_create_time'])) {
            $start_time = strtotime($getData['start_birthday']);
            $end_time = strtotime($getData['end_birthday']);
            $sql = $sql->whereBetweenTime('v.create_time', $start_time, $end_time);
        }
        //生日查询
        if (isset($getData['start_birthday']) && !empty($getData['start_birthday']) && isset($getData['end_birthday']) && !empty($getData['end_birthday'])) {
            $start_time = strtotime($getData['start_birthday']);
            $end_time = strtotime($getData['end_birthday']);
            $sql = $sql->whereBetweenTime('v.birthday', $start_time, $end_time);
        }
        //本金区间
        if (isset($getData['start_amount']) && !empty($getData['start_amount']) && isset($getData['end_amount']) && !empty($getData['end_amount'])) {
            $sql = $sql->whereBetween('v.amount', $getData['start_amount'], $getData['end_amount']);
        }

        //赠送金额
        if (isset($getData['start_give_amount']) && !empty($getData['start_give_amount']) && isset($getData['end_give_amount']) && !empty($getData['end_give_amount'])) {
            $sql = $sql->whereBetween('v.give_amount', $getData['start_give_amount'], $getData['end_give_amount']);
        }

        //充值总金额
        if (isset($getData['start_total_amount']) && !empty($getData['start_total_amount']) && isset($getData['end_total_amount']) && !empty($getData['end_total_amount'])) {
            $sql = $sql->whereBetween('v.total_amount', $getData['start_total_amount'], $getData['end_total_amount']);
        }
        //赠送总金额
        if (isset($getData['start_give_total_amount']) && !empty($getData['start_give_total_amount']) && isset($getData['end_give_total_amount']) && !empty($getData['end_give_total_amount'])) {
            $sql = $sql->whereBetween('v.give_total_amount', $getData['start_give_total_amount'], $getData['end_give_total_amount']);
        }
        $list = $sql->paginate($data['limit'])->each(function ($item) {
            $item['avatar'] = get_img_path($item['avatar']);
        });
        $this->result('获取成功', $list, 200);
    }

    /**
     * 会员卡查询
     */
    public function search()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['type']) || empty($getData['type'])) {
                $this->result('缺少参数', '', 204);
            }
            //手机号
            if ($getData['type'] == 1 && !empty($getData['mobile'])) {
                $where[] = ['mobile', 'like', '%' . $getData['mobile'] . '%'];
            } elseif ($getData['type'] == 2 && !empty($getData['card_no'])) {
                //卡号
                $where[] = ['card_no', 'like', '%' . $getData['card_no'] . '%'];
            } else {
                $this->result('缺少参数', '', 204);
            }
            $data = Db::name('qt_viper_card')
                ->field('vc.id,vc.mobile,vc.card_no,vc.amount,vt.name,vc.name as card_name,vc.give_amount,vc.viper_type_id')
                ->alias('vc')
                ->leftJoin('qt_viper_type vt', 'vc.viper_type_id = vt.id')
                ->where($where)
                ->where('vc.status', '1')
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 会员卡详情
     */
    public function detail()
    {
        $data = $this->request->post();

        if (empty($data['viper_card_id']))
            $this->result('缺少必要参数', '', 204);

        $info = ViperCardModel::get($data['viper_card_id']);

        $recharges = ViperCardRechargeLog::getLists($this->userInfo['id'], $data['viper_card_id'], 'id,amount,give_amount,create_time');

        foreach ($recharges as $key => $item) {
            $lists[$key]['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
        }

        $info['recharge'] = $recharges;
        $pays = ViperCardModel::getOrdersOfCard($this->userInfo['id'], $data['viper_card_id'], 'total_price,created_time');
        foreach ($pays as $key => $value) {
            $pays[$key]['cash_name'] = $this->userInfo['real_name'];
            $pays[$key]['cash_name'] = date('Y-m-d H:i:s', $data['created_time']);
        }

        $info['pay'] = $pays;
        $info['engineer'] = ViperCardModel::getEngineerOfCard($this->userInfo['id'], $data['viper_card_id']);
        $info['avatar'] = get_img_path($info['avatar']);
        $info['viper_type_name'] = \app\common\model\ViperType::where(['id'=>$info['viper_type_id']])->value('name');

        $this->result('获取成功', $info, 200);

    }


    /**
     * 基本数据--会员类型管理--会员类型列表
     */
    public function type_lists()
    {
        if ($this->request->isPost()) {
            $list = Db::name('qt_viper_type')
                ->where(['store_id' => $this->userInfo['store_id']])
                ->field('id,name,amount_percentage,give_amount_percentage')
                ->select();
            $this->result('获取成功', $list, 200);
        } else {
            $this->result('请求错误', '', 204);
        }
    }

    /**
     * 消费明细
     */
    public function consume_detail()
    {
        $post = $this->request->post();
        $limit = !empty($post['limit']) ? $post['limit'] : 10;
        if (empty($post['user_id'])) {
            $this->result('会员ID不能为空', '', 204);
        }

        $query = Db::name('qt_check_out_pay')
            ->alias('pay')
            ->field([
                'out.store_id',//会员所在门店
                'out.order_no',//结账单号
                'out.cashier_time',//结账时间
                'out.cashier_id',//结账人
                //'out.cashier_id',//积分
                'out.order_type',//订单状态
                'out.pay_content',//支付内容
                'pay.viper_card_id',//会员卡ID
                'pay.pay_money as total_money'
            ])
            ->leftJoin("qt_check_out out", 'pay.check_out_id=out.id')
            ->leftJoin("qt_viper_card card", 'card.id=out.viper_card_id')
            ->leftJoin('qt_viper_type type', 'card.viper_type_id=type.id')
            ->where('pay.store_id', $this->userInfo['store_id'])
            ->where(['pay.viper_card_id'=> $post['user_id'],'pay.type'=>'2']);

        $list = $query->order('out.id desc')
            ->paginate($limit)->each(function ($item) {
            //$item['pay_content'] = '[{"pay_type":"微信","pay_money":100},{"pay_type":"支付宝","pay_money":111}]';

            $item['cashier_name'] = Db::name('qt_users')->where('id', $item['cashier_id'])->value('real_name');
            $pay_content_json = json_decode($item['pay_content'], true);
            if (!empty($pay_content_json)) {
                $item['pay_content'] = implode(',', array_column($pay_content_json, 'pay_type'));
            }
            $order_type = [1 => '正常订单', 2 => '挂账单'];
            $item['order_type'] = $order_type[$item['order_type']];
            $item['store_name'] = Db::name('qt_store')->where('id', $item['store_id'])->value('name');
            $item['card_no'] = Db::name('qt_viper_card')->where('id', $item['viper_card_id'])->value('card_no');
            $item['money_log'] = Db::name('qt_viper_money_log')
                ->where('id', $item['order_no'])
                ->where(['type' => 1, 'check' => 1, 'flag' => 3,])
                ->value('money');
            return $item;
        });
        $this->result('查询成功', $list, 200);
    }


    /**
     * 会员卡充值
     */
    public function recharge()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'viper_card_id' => 'require',
                'template_id' => 'require',
                'template_type' => 'require',
            ];
            $message = [
                'viper_card_id.require' => '会员卡ID不能为空',
                'template_id.mobile' => '充值模版不能为空',
                'template_type.require' => '充值类型不能为空',
            ];
            $validate = new Validate($rule, $message);
            if (!$validate->check($post)) {
                $this->result($validate->getError(), '', 204);
            }
            $card_res = Db::name('qt_viper_card')->where('id', $post['viper_card_id'])->find();
            if (empty($card_res)) {
                $this->result('会员卡不存在', '', 204);
            }
            if ($post['template_type'] == TemplateConstant::TEMPLATE_TYPE_DEFAULT) {
                $template_res = Db::name('qt_viper_recharge_template')->where('id', $post['template_id'])->find();
                //$userViper = Db::name('qt_user_viper')->where('id', $card_res['user_id'])->find();
                //判断是否有返还金额
                $give_amount = ViperCardModel::returnAmount($post['viper_card_id'], $post['template_id']);
                $insert = [
                    'store_id' => $this->userInfo['store_id'],//门店
                    //'viper_user_id' => $userViper['id'],//会员ID
                    'viper_card_id' => $post['viper_card_id'],//会员卡id
                    'amount' => $template_res['amount'],//充值金额
                    'give_amount' => $give_amount,//赠送金额
                    'after_amount' => $card_res['amount'],//充值之前金额
                    'recharge_temp_name' => $template_res['name'],//充值模板名称
                    'recharge_tempid' => $template_res['id'],//充值模板id
                    'pay_status' => 1,//支付状态 0 未支付 1 正常 3 已撤销
                    'pay_time' => time(),//支付时间
                    'order_no' => create_card_recharge(),//支付单号
                    'pay_content' => $post['pay_content'],//支付方式 1 微信 2 支付宝
                    'integral' => $template_res['integral'],//赠送的积分数量
                    'type' => 2,//卡片状态 1开卡 2 充值
                    'card_amount' => $template_res['amount'] + $give_amount,//入卡金额
                    'sale_id' => !empty($post['sale_id']) ? $post['sale_id'] : 0,//销售人
                    'commission' => number_format(($template_res['amount'] * $template_res['rate']) / 100, 2),//提成
                    'payee' => $this->userInfo['id'],//收款人
                    'collection_time' => time(),//收款时间
                    'card_type' => TemplateConstant::TEMPLATE_TYPE_DEFAULT,//卡片类型：1充值，2次卡，3 月卡
                    'is_first' => 2,//1 首充 2 续充
                    'recharge_content' => $post['recharge_content'],//充值备注
                    'creater' => $this->userInfo['id'],
                    'updater' => $this->userInfo['id'],
                    'create_time' => time(),
                    'update_time' => time(),
                ];

                //更新会员卡数据
                $viper_card = [
                    'amount' => $card_res['amount'] + $template_res['amount'],
                    'give_amount' => $card_res['give_amount'] + $give_amount,
                    'give_total_amount' => $card_res['give_total_amount'] + $give_amount,
                    'total_amount' => $card_res['total_amount'] + $template_res['amount'],
                    'score' => $card_res['score'] + $template_res['integral'],//积分
                ];
//                try {
//                    Db::startTrans();
                    //插入日志
                    $recharge_log_id = Db::name('qt_viper_card_recharge_log')->insertGetId($insert);
                    //更新会员卡
                    Db::name('qt_viper_card')->where('id', $post['viper_card_id'])->update($viper_card);
                    //更新用户
                    //Db::name('qt_user_viper')->where('id', $card_res['user_id'])->update($user);

                    check_out_pay_all($post['pay_content'], $recharge_log_id, $this->userInfo, '1');

                    //写提成记录
                    $commission_data = $post;
                    $commission_data['store_id'] = $this->userInfo['store_id'];
                    $commission_data['viper_type_id'] = $card_res['viper_type_id'];
                    $commission_data['sale_id'] = !empty($post['sale_id']) ? $post['sale_id'] : 0;
                    ViperCardModel::rechargeCommission($commission_data, $recharge_log_id, $post['viper_card_id'], 4,'2');

                    //打印普通充值单
                    FeiEPrintService::printPhoneEntry(['viper_card_id' => $post['viper_card_id'], 'recharge_log_id' => $recharge_log_id], $this->userInfo);

                    //发送短信
                    //Alisms::rechargeSend($recharge_log_id);
                    //处理优惠券
                    if (!empty($post['coupon'])) {
                        $coupon = json_decode($post['coupon'], true);
                        TicketService::sendTicket($coupon, $this->userInfo, $card_res);
                    }
                    ViperCardModel::saveMoneyLog($post['viper_card_id'],$insert['card_amount']);//资金变动记录
//                } catch (Exception $exception) {
//                    Db::rollback();
//                    $this->result('充值失败', '', 204);
//                }
            }
            $this->result('充值成功', '', 200);

        }
    }

    /**
     * 会员充值详情
     */
    public function open_detail()
    {
        $data = $this->request->post();
        if (!isset($data['limit']) || empty($data['limit'])) {
            $data['limit'] = '10';
        }
        $already = Db::name('qt_viper_card_recharge_log')
            ->field('l.id,l.status,l.pay_status,s.name as store_name,t.id as template_id,t.name as template_name,l.create_time,l.integral,l.amount,l.give_amount,l.status,u.real_name')
            ->alias('l')
            ->leftJoin('qt_store s ', 's.id = l.store_id')
            ->leftJoin('qt_viper_recharge_template t ', 't.id = l.recharge_tempid')
            ->leftJoin('qt_users u ', 'u.id = l.creater')
            ->where(['l.viper_card_id' => $data['id'], 'l.pay_status' => '1', 'l.card_type' => '1'])
            ->paginate($data['limit'])->each(function ($item) {
                $item['return_money'] = '';
                $content = Db::name('qt_viper_recharge_template_return')
                    ->field('amount,times')
                    ->where('template_id', $item['template_id'])
                    ->select();
                if (!empty($content)) {
                    foreach ($content as $key => $value) {
                        $returnMoney[$key] = '第' . $value['times'] . '个月' . '返还' . $value['amount'] . '元';
                    }
                    $item['return_money'] = implode(',', $returnMoney);
                }
                return $item;
            });
        $this->result('查询成功', $already, 200);
    }

    /**
     *技师信息
     */
    public function engineerDetail(){
        $getData = $this->request->post();
        if(empty($getData['viper_card_id'])){
            $this->result('请选择会员卡', '', 204);
        }
        $average = 0;
        $checkOutIds = Db::name('qt_check_out_pay')->where(['viper_card_id'=>$getData['viper_card_id'],'type'=>'1'])->column('check_out_id');
        $totalMoney = Db::name('qt_check_out')->whereIn('id',$checkOutIds)->sum('total_money');
        $engineer = Db::name('qt_check_out')->whereIn('id',$checkOutIds)->column('engineer_ids');
        //所有的技师出现次数
        $engineerData = implode(',',$engineer);
        $resultEngineer = [];
        if($engineerData != ""){
            $engineerDataArray = explode(',',$engineerData);
            $engineerDataCount = array_count_values($engineerDataArray);
            foreach ($engineerDataCount as $key=>$value){
                $resultEngineer[$key]['number'] = $value;
                $resultEngineer[$key]['work_number'] = Db::name('qt_users')->where(['id'=>$key])->value('work_number');
            }
            $resultEngineer = array_values($resultEngineer);
            $number = count($checkOutIds);
            if($number != 0){
                $average = bcdiv($totalMoney,$number,2);
            }
        }
        $this->result('查询成功', ['average'=>$average,'list'=>$resultEngineer], 204);

    }


}
